import 'package:acgn_pioneer/models/comment_model.dart';
import 'package:flutter/widgets.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import '../../../public.dart';
import '../_index.dart';
import '../services/_index.dart';
import 'comment_item.dart';
import 'comment_title.dart';
import 'utils.dart';

/// 评论的回复
class ReaderCommentReply extends StatefulWidget {
  final CommentModel commentModel;
  final ComicModel comicModel;
  final ChapterModel chapterModel;

  ReaderCommentReply(
      {Key key, this.commentModel, this.comicModel, this.chapterModel})
      : super(key: key);

  @override
  ReaderCommentReplyState createState() => new ReaderCommentReplyState();
}

class ReaderCommentReplyState extends State<ReaderCommentReply> {
  List<CommentModel> listAll = [];
  ReaderCommentService readerCommentService = ReaderCommentService();
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  int totalCount = 0;
  int loadingType = 1; // 1：热门、2：最新
  bool hasInited = false; // 是否初始化完成
  bool hasMoreData = false; // 是否有更多加载帖子
  int page = 1; // 当前页码
  int pageSize = 20;

  @override
  void initState() {
    super.initState();
    doRequest();
  }

  // 重置请求相关状态
  resetRequestData() {
    page = 1;
    hasInited = false;
    listAll.clear();
  }

  // 获取热门评论
  getHotComments() async {
    var temps = await readerCommentService.getHotComment(
        page, widget.comicModel.id, 0,
        fatherid: widget.commentModel.id);
    hasMoreData = temps.length == pageSize; // 请求数量一致，说明还有数据
    if (temps.length > 0) {
      listAll.addAll(temps);
    }
    setState(() {});
  }

  // 获取普通评论
  getNormalComments({bool isWater = true}) async {
    var temps = await readerCommentService.getNormalComment(
        page, widget.comicModel.id, 0,
        isWater: false, fatherid: widget.commentModel.id);
    hasMoreData = temps.length == pageSize; // 请求数量一致，说明还有数据
    if (temps.length > 0) {
      listAll.addAll(temps);
    }
    setState(() {});
  }

  // 获取组装子评论
  getChildrenComments(List<CommentModel> lst) async {
    var ids = lst.map((e) => e.id).join(',');
    List<CommentModel> temps =
        await readerCommentService.getChildrenComment(ids);
    temps.forEach((temp) {
      var model = listAll.firstWhere((item) => item.id == temp.fatherId);
      model.lstChildren.add(temp);
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    ThemeProvider theme = Provider.of<ThemeProvider>(context);
    return Scaffold(
        backgroundColor: theme.primaryColor,
        resizeToAvoidBottomInset: false,
        appBar: AppBar(
            title: Text('评论回复'),
            leadingWidth: 44,
            leading: BackComponent(),
            backgroundColor: theme.primaryColor,
            centerTitle: true),
        body: buildBody());
  }

  buildBody() {
    var padding = EdgeInsets.only(left: 10, right: 10, top: 10, bottom: 20);
    return Column(children: [
      Expanded(
          child: Container(
              padding: EdgeInsets.only(left: 16, right: 16),
              child: Column(children: [
                Container(
                    width: double.infinity,
                    padding: padding,
                    decoration: BoxDecoration(
                        border: Border(
                            bottom: BorderSide(color: Colors.black, width: 1))),
                    child: ReaderCommentItem(
                        commentModel: widget.commentModel,
                        comicModel: widget.comicModel,
                        isReply: true)),
                Container(
                    padding: padding,
                    child: ReaderCommentTitle(
                      comicModel: widget.comicModel,
                      totalCount: widget.commentModel.revertCount,
                      isReply: true,
                      cliType: loadingType,
                      onTap: (int type) {
                        loadingType = type;
                        resetRequestData();
                        getList();
                      },
                    )),
                buildContent()
              ]))),
      CommentUtil.buildInput(
          placeholder: '回复：' + widget.commentModel.uName,
          onTap: () {
            CommentUtil.showInput(
                context,
                (context) => PopInputBoxComponent(
                    child: ReaderCommentInput(
                        chapterModel: widget.chapterModel,
                        isComicType: false,
                        placeholder: '回复：' + widget.commentModel.uName)));
          })
    ]);
  }

  buildContent() {
    if (!hasInited) {
      return Container(height: 400, child: LoadingComponent());
    }
    return Container(
        margin: EdgeInsets.only(top: 10),
        height: 420,
        child: buildView(ListView.builder(
            physics: ClampingScrollPhysics(),
            shrinkWrap: true,
            itemCount: listAll.length,
            itemBuilder: (context, index) {
              return ReaderCommentItem(
                  commentModel: listAll[index],
                  comicModel: widget.comicModel,
                  isReply: true);
            })));
  }

  Widget buildView(Widget widget) {
    return RefreshConfig(
        child: SmartRefresher(
            enablePullDown: true,
            enablePullUp: true,
            controller: _refreshController,
            onRefresh: _onRefresh,
            onLoading: _onLoading,
            footer: CustomFooter(builder: buildFooter),
            child: widget));
  }

  Widget buildFooter(BuildContext context, LoadStatus mode) {
    if (mode == LoadStatus.loading) {
      return LoadingComponent();
    }
    return SizedBox.shrink();
  }

  void _onRefresh() async {
    resetRequestData();
    await doRequest();
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    page++;
    await doRequest();
  }

  doRequest() async {
    await getList();
    if (!hasMoreData) {
      _refreshController.loadNoData();
      return;
    }
    _refreshController.loadComplete();
  }

  getList() async {
    switch (loadingType) {
      case 1:
        await getHotComments();
        break;
      case 2:
        await getNormalComments();
        break;
    }
    if (!hasInited) {
      // 设置初始化完成标志
      hasInited = true;
    }
  }
}
